package com.darker.yygh.user.api;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.model.user.UserInfo;
import com.darker.yygh.helper.JwtHelper;
import com.darker.yygh.result.Result;
import com.darker.yygh.user.service.UserInfoService;
import com.darker.yygh.user.utils.ConstantPropertiesUtil;
import com.darker.yygh.user.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/ucenter/wx")
public class WeixinApiController {

    @Autowired
    private UserInfoService userInfoService;

    //微信扫描后回调方法
    @GetMapping("callback")
    public String callback(String code, String state) {
        //使用code和appid以及appscrect换取access_token

        //拼接访问微信api的链接
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");

        //把参数设置进字符串
        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                code);

            String access_tokenInfo = null;
            //访问微信得api获取access_tokenInfo
        try {
            access_tokenInfo = HttpClientUtils.get(accessTokenUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //从access_tokenInfo中获取access_token和openid
            JSONObject jsonObject = JSONObject.parseObject(access_tokenInfo);//把字符串转换成json

            //通过key获取值
            String access_token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");

            //通过openid判断 该用户是否已经存在
            UserInfo userInfo = userInfoService.selectWxInfoOpenId(openid);
            if (userInfo == null) {
                //用openid access_token请求微信地址 得到扫码人的信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";

                String userInfourl = String.format(baseUserInfoUrl, access_token, openid);
                String resultInfo = null;
                try {
                    resultInfo = HttpClientUtils.get(userInfourl);
                } catch (Exception e) {
                    e.printStackTrace();
                }


                //获取用户微信的信息
                JSONObject userJson = JSONObject.parseObject(resultInfo);
                String nickname = userJson.getString("nickname"); //获取微信用户昵称

                //把用户信息保存到数据库
                userInfo = new UserInfo();
                userInfo.setNickName(nickname);
                userInfo.setOpenid(openid);
                userInfo.setStatus(1);
                userInfoService.save(userInfo);
            }
            Map<String, Object> map = new HashMap<>();
            String name = userInfo.getName();
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name", name);

            //判断该用户是否绑定了手机号  前端可通过openid的值判断是否绑定
            if (StringUtils.isEmpty(userInfo.getPhone())) {
                //如果没有绑定了手机号 返回openid
                map.put("openid", userInfo.getOpenid());
            } else {
                //如果绑定了手机号  返回空
                map.put("openid", "");
            }

            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token", token);

        try {
           name  = URLEncoder.encode((String) map.get("name"), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "redirect:" + ConstantPropertiesUtil.YYGH_BASE_URL + "/weixin/callback?token=" + map.get("token") +
                "&openid=" + map.get("openid") + "&name=" +name ;


    }


    //生成微信二维码
    //返回生成二维码参数
    @GetMapping("getLoginParam")
    @ResponseBody
    public Result genQrConnect() {
        String redirectUri = null;
        try {
            redirectUri = URLEncoder.encode(ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL, "UTF-8");
            Map<String, Object> map = new HashMap<>();
            map.put("appid", ConstantPropertiesUtil.WX_OPEN_APP_ID);
            map.put("redirect", redirectUri);
            map.put("scope", "snsapi_login");
            map.put("state", System.currentTimeMillis() + "");//System.currentTimeMillis()+""
            return Result.ok(map);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }


    }

}
